<template>
  <van-popup
    v-model:show="show"
    round
    :closeable="!forceAgree"
    @close="handleClose"
    class="privacy-popup"
  >
    <div class="privacy-container">
      <div class="title">{{ title }}</div>
      <div
        class="privacy-content"
        ref="privacyContentRef"
        @scroll="handleScroll"
        :class="{ 'has-reached-bottom': state.hasToBottomed }"
      >
        <slot></slot>
        <!-- 滚动到底部提示 -->
        <div v-if="state.hasToBottomed" class="bottom-indicator">已阅读至底部</div>
      </div>
      <div class="footer">
        <van-button
          class="btn-agree"
          type="primary"
          block
          :disabled="state.btnDisabled"
          @click="handleAgree"
          :loading="state.isLoading"
        >
          {{ btnText }}
          <span v-if="showCountdown">({{ state.remainingTime }}秒)</span>
        </van-button>
        <van-button
          type="primary"
          block
          plain
          @click="handleClose"
          :disabled="forceAgree"
        >
          我不同意
        </van-button>
      </div>
    </div>
  </van-popup>
</template>

<script setup>
import { ref, reactive, defineProps, defineEmits, watch, onUnmounted, computed } from 'vue';

// 节流函数 - 优化滚动事件性能
const throttle = (fn, delay = 30) => {
  let lastTime = 0;
  return (...args) => {
    const now = Date.now();
    if (now - lastTime >= delay) {
      fn.apply(this, args);
      lastTime = now;
    }
  };
};

const privacyContentRef = ref(null);
const show = ref(false);

// 使用reactive统一管理状态，提高可维护性
const state = reactive({
  btnDisabled: true,
  remainingTime: 0,
  hasToBottomed: false,
  isLoading: false,
  timeoutTimer: null,
  intervalTimer: null
});

// 定义props并添加类型验证和默认值
const props = defineProps({
  title: {
    type: String,
    default: '隐私政策'
  },
  modelValue: {
    type: Boolean,
    default: false
  },
  btnText: {
    type: String,
    default: '我已阅读并同意'
  },
  timeOut: {
    type: Number,
    default: 0
  },
  forceAgree: {
    type: Boolean,
    default: false // 是否强制同意，为true时"我不同意"按钮禁用
  },
  scrollThreshold: {
    type: Number,
    default: 10 // 滚动到底部的阈值
  }
});

const emits = defineEmits(['update:modelValue', 'agree']);

// 计算属性 - 简化模板逻辑
const showCountdown = computed(() => props.timeOut > 0 && state.remainingTime > 0);

// 检查是否滚动到底部
const checkScrollToBottom = () => {
  if (!privacyContentRef.value) return false;
  const { scrollTop, clientHeight, scrollHeight } = privacyContentRef.value;
  return scrollHeight - clientHeight - scrollTop <= props.scrollThreshold;
};

// 开始倒计时
const startCountdown = () => {
  // 清除可能存在的定时器
  clearInterval(state.intervalTimer);
  state.remainingTime = props.timeOut;

  state.intervalTimer = setInterval(() => {
    state.remainingTime--;
    if (state.remainingTime <= 0) {
      clearInterval(state.intervalTimer);
      state.btnDisabled = false;
    }
  }, 1000);
};

// 滚动事件处理（带节流）
const handleScroll = throttle(() => {
  if (!privacyContentRef.value) return;
  if(!state.hasToBottomed) {
    const hasReachedBottom = checkScrollToBottom();
    state.hasToBottomed = hasReachedBottom;
    if (props.timeOut > 0) {
      if (!hasReachedBottom) {
        state.btnDisabled = true;
        clearInterval(state.intervalTimer);
      } else {
        startCountdown();
      }
    } else {
      // 无超时设置时，滚动到底部立即启用按钮
      state.btnDisabled = !hasReachedBottom;
    }
  }
});

// 关闭弹窗
const handleClose = () => {
  // 清除所有定时器
  clearTimeout(state.timeoutTimer);
  clearInterval(state.intervalTimer);
  // 重置状态
  Object.assign(state, {
    btnDisabled: true,
    remainingTime: 0,
    hasToBottomed: false,
    timeoutTimer: null,
    intervalTimer: null
  });
  // 重置滚动位置
  if (privacyContentRef.value) {
    privacyContentRef.value.scrollTop = 0;
  }
  emits('update:modelValue', false);
};

// 同意隐私政策
const handleAgree = () => {
  state.isLoading = true;
  // 模拟可能的异步操作
  setTimeout(() => {
    state.isLoading = false;
    handleClose();
    emits('agree');
  }, 500);
};

// 监听显示状态变化
watch(
  () => props.modelValue,
  (newVal) => {
    show.value = newVal;
    // 重置状态
    if (newVal) {
      state.remainingTime = props.timeOut;
      state.btnDisabled = true;
      state.hasToBottomed = false;
    }
  },
  { immediate: true }
);

// 组件卸载时清理
onUnmounted(() => {
  clearTimeout(state.timeoutTimer);
  clearInterval(state.intervalTimer);
});
</script>

<style lang="scss" scoped>
.privacy-container {
  height: 80vh;
  width: 90vw;
  max-width: 500px; // 限制最大宽度，优化大屏幕体验
  padding: 15px;
  position: relative;
  box-sizing: border-box;

  .title {
    font-size: 20px;
    font-weight: bold;
    margin-bottom: 15px;
    text-align: center;
    color: #333;
  }

  .privacy-content {
    height: calc(100% - 140px);
    overflow-y: auto;
    padding-right: 5px;
    font-size: 14px;
    line-height: 1.6;
    color: #666;
    transition: background-color 0.3s ease;

    // 滚动到底部的提示
    .bottom-indicator {
      text-align: center;
      padding: 10px;
      color: #07c160;
      font-size: 13px;
    }

    // 滚动到底部时的样式变化
    &.has-reached-bottom {
      background-color: rgba(7, 193, 96, 0.05);
    }
  }

  .footer {
    position: absolute;
    bottom: 15px;
    left: 15px;
    width: calc(100% - 30px);

    .btn-agree {
      margin-bottom: 10px;
      transition: all 0.3s ease;

      &:not(:disabled) {
        background-color: #07c160;
        transform: scale(1.02);
      }

      &:disabled {
        opacity: 0.7;
      }
    }
  }
}

// 自定义滚动条样式
::v-deep .privacy-content::-webkit-scrollbar {
  width: 6px;
}

::v-deep .privacy-content::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 10px;
}

::v-deep .privacy-content::-webkit-scrollbar-thumb {
  background: #ddd;
  border-radius: 10px;
}

::v-deep .privacy-content::-webkit-scrollbar-thumb:hover {
  background: #ccc;
}
</style>